package com.danke.lib.banner.anim;

import android.view.View;

import com.nineoldandroids.animation.ObjectAnimator;

import androidx.annotation.NonNull;

/**
 * 宽度可变
 *
 * @author wpq
 * @version 1.0
 */
public class WidthAnimator extends BaseAnimator {

    private static final String PROPERTY_NAME = "width";
    private static final int DURATION = 250;

    private int mWidth;

    private WidthAnimator(int width) {
        this.mWidth = width;
        this.mDuration = DURATION;
    }

    public static WidthAnimator newInstance(int width) {
        return new WidthAnimator(width);
    }

    @Override
    public void setAnimation(@NonNull View view) {
        if (mWidth > 0) {
            ViewWrapper wrapper = new ViewWrapper(view);
            this.mAnimatorSet.playTogether(ObjectAnimator.ofInt(wrapper, PROPERTY_NAME, mWidth));
        }
    }

    private static class ViewWrapper {

        private View mTarget;

        public ViewWrapper(View target) {
            mTarget = target;
        }

        /**
         * 根据 {@link #PROPERTY_NAME} 生成对应set和get方法
         * 调用属性动画如：ObjectAnimator.ofInt(target, "width", 30)，此时 propertyName 为 width,
         * 最终会调用 target 的 setWidth 方法，即 set + Width(首字母大写)，
         * 具体代码查看 {@link com.nineoldandroids.util.ReflectiveProperty}
         * ！！由于这里是反射调用，所以一定要记得处理混淆！！
         */
        @SuppressWarnings("JavadocReference")
        public void setWidth(int width) {
            try {
                mTarget.getLayoutParams().width = width;
                mTarget.requestLayout(); //必须调用，否则宽度改变但UI没有刷新
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public int getWidth() {
            try {
                return mTarget.getLayoutParams().width;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return 0;
        }
    }
}
